package com.feshfans.controller.special;

import com.feshfans.bridge.MessageBridge;
import com.feshfans.controller.RegisteredController;
import com.feshfans.xmpp.client.AccountClient;
import com.feshfans.xmpp.client.ClientFactory;
import com.feshfans.xmpp.client.MessageClient;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.ResourceBundle;

public class MessageController extends RegisteredController<BareJid> implements Initializable {

    private static final Logger Log = LoggerFactory.getLogger(MessageController.class);

    @FXML private TextArea sendTextArea;
    @FXML private TextArea historyTextArea;
    @FXML private VBox vCardVBox;

    // 记录和哪个好友开启的会话窗口
    private BareJid jid;
    private MessageBridge messageNotify;
    private MessageClient messageClient;
    private AccountClient accountClient;

    public MessageController(){
        // 获取 client ，并注册到消息通知
        messageClient = ClientFactory.getClient(ClientFactory.ClientType.Message);
        accountClient = ClientFactory.getClient(ClientFactory.ClientType.Account);
        messageNotify= MessageBridge.getInstance();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        historyTextArea.setEditable(false);
    }

    @Override
    public void onLoad(BareJid o) {
        //初始化必要的数据
        if(o instanceof BareJid){
            BareJid bareJid = (BareJid)o;
            this.jid = bareJid;
        } else {
            throw new RuntimeException(this.getClass().getName() + "{} onLoad 函数参数错误");
        }

        // 加载好友的 VCard
        loadVCard();

    }

    private void loadVCard(){
        String jid = getJid();
        Log.debug("jid:{}");
        try {
            VCard vCard = accountClient.getVCard(JidCreate.entityBareFrom(jid));
            if(vCard == null){
                Log.info("未获取到指定好友的 VCard, jid{}",jid);
                return;
            }
            Label nickName = new Label();
            nickName.setText("昵称:"+vCard.getNickName());

            Label fullName = new Label();
            fullName.setText("姓名:"+vCard.getFirstName()+vCard.getMiddleName()+vCard.getLastName());

            Label homeEmail = new Label();
            homeEmail.setText(vCard.getEmailHome());

            vCardVBox.getChildren().addAll(nickName,fullName,homeEmail);
        } catch (Exception e) {
            Log.error("获取好友 VCard 出错，jid:{}",jid,e);
        }
    }


    @FXML
    private void sendMessage(){

        String message = sendTextArea.getText();
        if(StringUtils.isEmpty(message)){
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText("内容不能为空");
            alert.show();
            return;
        }
        String to = getJid();
        try {
            messageClient.sendMessage(to,message);
            handlerSendText();
            return;
        } catch (Exception e) {
            Log.error("发送消息失败,to: {},message:{}",to,message,e);
        }
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setContentText("发送失败");
        alert.show();
        return;
    }

    private void handlerSendText(){
        String message = sendTextArea.getText();
        sendTextArea.clear();
        String historyText = historyTextArea.getText();
        StringBuilder builder = new StringBuilder(historyText);
        builder.append("\r\n");
        builder.append("我 : ");
        builder.append(message);
        historyTextArea.setText(builder.toString());
    }
    private void handlerReceiveText(String from,String body){
        String historyText = historyTextArea.getText();
        StringBuilder builder = new StringBuilder(historyText);
        builder.append("\r\n");
        builder.append(from+" : ");
        builder.append(body);
        historyTextArea.setText(builder.toString());
    }

    /**
     * 收到消息后，显示数据
     */
    public void newIncomingMessage(EntityBareJid fromJid, String body){
        handlerReceiveText(fromJid.getLocalpart().toString(),body);
    }

    public String getJid() {
        return this.jid.toString();
    }

    @Override
    public void register() {
        messageNotify.register(this);
    }

    @Override
    public void unregister() {
        messageNotify.unregister(this);
    }
}
